#pragma once
#include "Sock.hpp"
#include "log.hpp"
#include <sys/select.h>
#include <sys/time.h>

#define NUM sizeof(fd_set) * 8
#define FD_NONE -1
static const uint16_t g_port = 8080;

class selectServer
{

public:
    selectServer(uint16_t port = g_port) : _port(port)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock, port);
        Sock::Listen(_listensock);
        _fd_arr[0] = _listensock;
        for (int i = 1; i < NUM; i++)
        {
            _fd_arr[i] = FD_NONE;
        }
        logMessage(DEBUG, "create server success");
    }
    void start()
    {
        while (true)
        {
            // Debug();
            sleep(1);
            //struct timeval timeout = {0, 0};
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = _listensock;
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_arr[i] == FD_NONE)
                    continue;
                FD_SET(_fd_arr[i], &rfds);
                if (_fd_arr[i] > maxfd)
                    maxfd = _fd_arr[i];
            }

            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            // int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                logMessage(DEBUG, "time out.....");
                break;
            case -1:
                logMessage(WARNING, "select error,errno:%d,strerrno:%s", errno, strerror(errno));
                break;
            default:
                logMessage(DEBUG, "get a new link success");
                handlerEvent(rfds);
                break;
            }
        }
    }
    ~selectServer()
    {
        if(_listensock > 0) close(_listensock);
    }

private:
    void handlerEvent(const fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_arr[i] == FD_NONE)
                continue;
            if (FD_ISSET(_fd_arr[i], &rfds))
            {
                if (_fd_arr[i] == _listensock)
                    Accpeter();
                else
                    Recver(i);
            }
        }
    }
    void Accpeter()
    {
        std::string clientip;
        uint16_t clientport = 0;
        int sock = Sock::Accept(_listensock, &clientip, &clientport);
        if (sock < 0)
        {
            logMessage(WARNING, "accept error");
            return;
        }
        logMessage(DEBUG, "get a new link,[%s:%d],sock:%d", clientip.c_str(), clientport, sock);
        int pos = 1;
        for (; pos < NUM; pos++)
        {
            if (_fd_arr[pos] == FD_NONE)
                break;
        }
        if (pos == NUM)
        {
            logMessage(WARNING, "fd is not enough,close sock");
            close(sock);
        }
        else
        {
            _fd_arr[pos] = sock;
        }
    }
    void Recver(int pos)
    {
        logMessage(DEBUG, "message in,get IO event:%d", _fd_arr[pos]);
        char buffer[1024];
        ssize_t n = recv(_fd_arr[pos], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            logMessage(DEBUG, "client[%d]:%s", _fd_arr[pos], buffer);
        }
        else if (n == 0)
        {
            logMessage(DEBUG, "client[%d] quit,me too", _fd_arr[pos]);
            close(_fd_arr[pos]);
            _fd_arr[pos] = FD_NONE;
        }
        else
        {
            logMessage(WARNING, " %d sock recv error, %d : %s", _fd_arr[pos], errno, strerror(errno));
            close(_fd_arr[pos]);
            _fd_arr[pos] = FD_NONE;
        }
    }
    void Debug()
    {
        std::cout << "_fd_arr[]:";
        for(int i = 0; i < NUM;i++)
        {
            if(_fd_arr[i] == FD_NONE) continue;
            std::cout << _fd_arr[i] << " ";
        }
        std::cout << std::endl; 
    }

private:
    int _listensock;
    uint16_t _port;
    int _fd_arr[NUM];
};